var express = require('express');
var router = express.Router();
var Album = require('./model');
var moment = require('moment');
moment.locale('zh-cn');
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const md5 = require('md5');

let storage = multer.diskStorage({
 	destination: function (req, file, cb) {
   		cb(null, path.join(__dirname, '..', 'public', 'tmp'))
 	},
 	filename: function (req, file, cb) {
   		let fileFormat =(file.originalname).split(".");
   		cb(null, file.fieldname + '-' + md5(file) + "." + fileFormat[fileFormat.length - 1]);
 	}
})

//中间件
const upload = multer({
  storage: storage
});
const single = upload.single("myfile");

//获取某个相册下的图片
router.post('/image/list', async function(req, res, next) {
	//console.log(req.body.name);
	const id = req.body.id;
	let data = [];
	let arr;
	if(!id || id === 'all'){
		arr = await Album.find();
	} else {
		arr = await Album.find({_id: id})
	}
	arr.forEach(function(item, i){
		item.imageList.forEach(function(path, j){
			path && data.push(path);
		})
	})
	//console.log(data);
  	res.send({status: '0', data})
});


//获取相册列表
router.post('/list', async function(req, res, next){
	let data = [];
	let arr = await Album.find();
	// console.log('相册列表', arr);
	arr.forEach(function(item, i){
		item.name && data.push({
			id: item._id,
			name: item.name
		})
	})
	//console.log(data);
	res.send({status: '0', data});
})
//创建相册
router.post('/create', async function(req, res, next){
	const name = req.body.name;
	console.log(name)
	console.log(await Album.find({name}))
	if(await Album.find({name}).length === 0){
		res.send({status: '-1', message: '相册名重复'});
	}else {
		let album = new Album({name, createDate: moment().format('YYYY-MM-DD')});
		await album.save()
		res.send({status: '0'});
	}
})
//删除相册
router.get('/delete', async function(req, res, next){
	let albumId = req.query.albumId;
	//console.log('相册ID', albumId);
	await Album.remove({_id: albumId});
	//console.log(Album.find())
	res.send({status: '0'});
})


//上传图片
router.post('/image/add', single, async function(req, res){
	// res.send('文件上传成功')
    //console.log(req);
    // console.log(req.files);
    // console.log(req.body.albumId);
  if (req.file) {
       	
       	let file = req.file
       	let albumId = req.body.albumId;
       	let sourceFile = path.join('tmp', file.filename);
       	let album = await Album.find({_id: albumId});
       	let imageList = album[0].imageList;
       	imageList.push({
       		path: sourceFile,
       		createDate: moment().format('YYYY-MM-DD')
       });
       await Album.findOneAndUpdate({_id: albumId}, {imageList});
       res.send({status: '0'});

   }
})

//删除图片
router.get('/image/delete', async function(req, res){
	let id = req.query.id;
	// console.log(id);
	let data = await Album.find({'imageList._id': id});
	var path;
	data[0].imageList.forEach(function(item, i){
		console.log(item._id, id, item._id === id);
		if(item._id === id){
			path = item.path;
		}
	});

	// fs.unlink(namePath, function(err){
 //      if(err){
 //        res.send({status: -1});
 //      }
 //      res.send({status: 0});
 //    })
	console.log(path);
	res.send({status: '0'})
})

module.exports = router;